package org.high5.dataprovider;




import org.high5.model.*;



import java.util.ArrayList;
import java.util.Random;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDBAdapter {
	
	// atributes'names
	private static final String KEY_ROWID = "_id";
	private static final String KEY_LONGITUDE = "longtitude";
	private static final String KEY_LATITUDE = "latitude";
	private static final String KEY_ALTITUDE = "altitude";
	private static final String KEY_ACCURACY = "accuracy";
	private static final String KEY_DATE = "date_field";
	
	private static final String USER_ROWID = "_id";
	private static final String USER_SECONDS = "soconds";
	private static final String USER_WORKING = "working";
	
	
	// debugging tag
	private static final String TAG = "MyDBAdapter";
	
	// database information
	private static final String DATABASE_NAME = "MyDB";
	private static final String DATABASE_TABLE = "location";
	private static final String USER_TABLE = "user_table";
	private static final int DATABASE_VERSION = 26;
	
	// the SQL code that creates the database
	private static final String DATABASE_CREATE = 
			"create table " + DATABASE_TABLE + " ( "
			+ KEY_ROWID + " integer primary key autoincrement, "
			+ KEY_LONGITUDE + " text not null, "
			+ KEY_LATITUDE + " text not null, "
			+ KEY_ALTITUDE + " text not null, "
			+ KEY_ACCURACY + " text, "
			+ KEY_DATE + " integer not null )"; // this is a unix time format (in java use the "long" type)
	
	private static final String USER_DATA_CREATE = 
			"create table " + USER_TABLE + " ( "
			+ USER_ROWID + " integer primary key autoincrement, "
			+ USER_SECONDS + " integer not null, "
			+ USER_WORKING + " integer not null )"; // this is a unix time format (in java use the "long" type)
	
	// essential variables for the adapter
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	
	public MyDBAdapter(Context ctx){
		// constructor of the Adapter
		
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}
	
	private static class DatabaseHelper extends SQLiteOpenHelper{

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
			
		}
		

		@Override
		public void onCreate(SQLiteDatabase db) {
			// when creating use the creation string from above
			Log.i(TAG, "In onCreate()");
			try{
				db.execSQL(DATABASE_CREATE);
				db.execSQL(USER_DATA_CREATE);
				Log.i(TAG, "CREATED!!!");
			} catch(SQLException e){ 
				// if there is a problem show a system msg
				Log.i(TAG, "NOT CREATED!!!");
				e.printStackTrace();
			}
			
			/************************* Populating *******************************/
				Random generator = new Random();
				for (int i=0; i<15; i++){
					String longit = String.format("%f", ((float)generator.nextInt(50)));
					String latit = String.format("%f", ((float)generator.nextInt(50)));
					String altit = String.format("%f", ((float)generator.nextInt(50)));
					String accur = String.format("%f", ((float)generator.nextInt(50)));
					long time = System.currentTimeMillis() / 1000L;
					String sql = "INSERT INTO "+ DATABASE_TABLE + " ("+
					KEY_LONGITUDE+","+KEY_LATITUDE+","+KEY_DATE+","+KEY_ALTITUDE+","+KEY_ACCURACY+
					") VALUES ("+longit+"," +latit+"," + time+"," + altit+"," + accur+")";
					db.execSQL(sql);
					
					
					String user = "INSERT INTO "+ USER_TABLE + " ("+
							USER_SECONDS+","+USER_WORKING+
							") VALUES (3,1)";
					db.execSQL(user);
					//insertLocation(longit, latit, time, altit, accur);
				}
				
			
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// destroys the old database and recreates it using onCreate() + system msg
			
			Log.w(TAG, "Updating database from version " + oldVersion + " to "
					+ newVersion + ", destroying old data");
			
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
			Log.i(TAG, "Table dropped");
			onCreate(db);
			
			
			
			
		}	
	}
	
	public MyDBAdapter open() throws SQLException{
		// opens the database
		
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	
	public void close(){
		// closes the database
		
		DBHelper.close();
	}
	
	public long insertLocation(String longitude, String latitude, long date, 
			String altitude, String accuracy){
		// add a single entry to the database
		
		
		
		
		ContentValues values = new ContentValues();
		values.put(KEY_LONGITUDE, longitude);
		values.put(KEY_LATITUDE, latitude);
		values.put(KEY_DATE, date);
		values.put(KEY_ALTITUDE, altitude);
		values.put(KEY_ACCURACY, accuracy);
		Log.i(TAG, "Location instered!");
		return db.insert(DATABASE_TABLE, null, values);
		
	}
	
	public boolean deleteContact(int rowId){
		// delete a row by given ID
		return db.delete(DATABASE_TABLE, KEY_ROWID + " = " + rowId, null) > 0;
	}
	
	public Cursor getAllLocations(){
		// query the database so that it returns all the records
		
		return db.query(DATABASE_TABLE, null,
				null, null, null, null, null);
	}
	
	public Cursor queryForPeriod( long start, long end){
		// queries the database returning records between startDate and endDate
		return db.query(DATABASE_TABLE, null, DATABASE_TABLE+"."+KEY_DATE + " > " 
				+ start + " AND " + DATABASE_TABLE+"."+KEY_DATE + " < " 
						+ end, null, null, null, null);
	}
	
	public boolean updateRecord(int rowId, String longitude, String latitude, long date, 
			String altitude, String accuracy){
		// updates a single record by given ID
		
		ContentValues values = new ContentValues();
		values.put(KEY_LONGITUDE, longitude);
		values.put(KEY_LATITUDE, latitude);
		values.put(KEY_DATE, date);
		values.put(KEY_ALTITUDE, altitude);
		values.put(KEY_ACCURACY, accuracy);
		return db.update(DATABASE_TABLE, values, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	public ArrayList<DataInfo> getAllLocationsInDataInfo(){
		// take the query and return an arraylist of datainfo with the data formatted as doubles
		Cursor query;
		
		query = db.query(DATABASE_TABLE, null, null, null, null, null, null);
		ArrayList<DataInfo> data = null;
		
		if (query.moveToFirst()){
			data = new ArrayList<DataInfo>();
			while(!(query.isAfterLast())){
				DataInfo dataInfo;
				String longi = query.getString(query.getColumnIndex(KEY_LONGITUDE));
				String lati = query.getString(query.getColumnIndex(KEY_LATITUDE));
				String alti = query.getString(query.getColumnIndex(KEY_ALTITUDE));
				dataInfo = new DataInfo(Double.parseDouble(lati), Double.parseDouble(longi),Double.parseDouble(alti));
				data.add(dataInfo);
				query.moveToNext();
			}
		}
		
		return data;
	}
	
	public ArrayList<DataInfo> getLocationsStartEndInDataInfo(long startDate, long endDate){
		// take the query and return an arraylist of datainfo with the data formatted as doubles
		Cursor query;
		
		query = queryForPeriod(startDate, endDate);
		ArrayList<DataInfo> data = null;
		
		if (query.moveToFirst()){
			data = new ArrayList<DataInfo>();
			
			while(!(query.isAfterLast())){
				DataInfo dataInfo;
				String longi = query.getString(query.getColumnIndex(KEY_LONGITUDE));
				String lati = query.getString(query.getColumnIndex(KEY_LATITUDE));
				String alti = query.getString(query.getColumnIndex(KEY_ALTITUDE));
				dataInfo = new DataInfo(Double.parseDouble(lati), Double.parseDouble(longi),Double.parseDouble(alti));
				data.add(dataInfo);
				query.moveToNext();
			}
		}
		
		return data;
	}
	
	public long insertUserPrefs(String seconds, String working){
		// add a single entry to the user table
		
		
		
		
		ContentValues values = new ContentValues();
		values.put(USER_SECONDS, seconds);
		values.put(USER_WORKING, working);
		Log.i(TAG, "User prefs inserted!");
		return db.insert(USER_TABLE, null, values);
		
	}
	
	public boolean updateUserPrefs(int rowId, String seconds, String working){
		// updates a single record by given ID
		
		ContentValues values = new ContentValues();
		values.put(USER_SECONDS, seconds);
		values.put(USER_WORKING, working);
		return db.update(USER_TABLE, values, USER_ROWID + "=" + rowId, null) > 0;
	}
	
	public Cursor getUserPrefs(){
		// query the database so that it returns all the records
		
		return db.query(USER_TABLE, null,
				null, null, null, null, null);
	}
	
	
	
	 
}